using Cysharp.Threading.Tasks;
using UnityEngine;

namespace Neatly.Module
{
    public class LogModule : ModuleSingleton<LogModule>
    {
        private static string m_ReceiveUrl = "";
        private bool m_IsDevelop;

        public override async UniTask Init()
        {
            Application.logMessageReceived += HandleLog;
        }

        private void HandleLog(string logString, string stackTrace, LogType type)
        {
            if (m_IsDevelop)
            {
                if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert)
                {
                    //打开报错页面
                }
            }
            if (string.IsNullOrEmpty(m_ReceiveUrl))
            {
                return;
            }
            DevelopLog(logString, stackTrace, type);
        }

        private void DevelopLog(string logString, string stackTrace, LogType type)
        {
            string result = $"{Application.identifier}|类型:{type} LogString:{logString}\n";
            ReportLog(result);
        }

        private void ReportLog(string msg)
        {
            HttpModule.Instance.PostJson(m_ReceiveUrl, "", msg).Forget();
        }

        public void SetIsDevelop(bool isDevelop)
        {
            m_IsDevelop = isDevelop;
        }

        public void SetReceiveUrl(string url)
        {
            m_ReceiveUrl = url;
        }
    }
}